<template>
  <div class="mapDiv" v-loading="loading">
    <!--地图-->
    <IndexMap v-if="completeRefreshData==true"
                  @getMap="getMap"
    ></IndexMap>
    <!--工具条控件-->
    <ControlToolBar v-if="completeRefreshData==true"
                    :map="map" :pageType="pageType" :mapDrawType="mapDrawType"
                    @getClickLonLat="getClickLonLat" @showQueryDiv="showQueryDiv"
                    @getAllDrawGeom="getAllDrawGeom" @getLonLatAddress="getLonLatAddress"
    ></ControlToolBar>
    <!--超图图层显示-->
    <SuperMapLayer v-if="completeMapBool==true"
                    :map="map" :layerDataTypeList="layerDataTypeList"
                    :resetClearAllBool="resetClearAllBool"
                    :clickLonLat="clickLonLat" :legendPosition="legendPosition"
    ></SuperMapLayer>
  </div>
</template>

<script setup>
//地图
import IndexMap from '@/map/informationRetrieval/historicalSeismicInformation/historicalSeismicEvent/indexMap.vue';
import ControlToolBar from '@/map/components/controlToolBar/map.vue';
import SuperMapLayer from '@/map/components/superMapLayer/index.vue';

const { proxy } = getCurrentInstance();
const props = defineProps(['dataType','formSqlFilter','drawGeomType','queryParams','queryFlag']);
const emits = defineEmits(['getDrawGeom','getAddress','returnQueryFlag']);
const loading = ref(false);
const pageType = ref("历史地震事件信息检索页面");

const data = reactive({
  //图层数据类别code和url列表
  layerDataTypeList:[
    {
      //历史地震事件
      level2DataType:"lsdz",//数据类别二级code
      level3DataType:"ls434ysqzml",//数据类别三级code
      versionCode:null,//查询临时图层过滤条件
      show:false,//是否显示
      isYw:false,//是否为业务系统数据，true业务系统，false基础数据系统
      tifFileName:null,//tif文件名称
    },
  ],
})
const { layerDataTypeList } = toRefs(data)

/*地图传参start*/
const completeRefreshData = ref(false);//防止刷新后地图不显示
const completeMapBool = ref(false);//是否完成加载地图
//地图对象
const map = ref(null);
const getMap = (obj)=>{
  map.value = obj;
  completeMapBool.value = true;
}
const legendPosition = ref("left_bottom");//图例显示位置
const resetClearAllBool = ref(false);//是否清空全部超图图层
//点击地图经纬度
const clickLonLat = ref([]);
//传递点击地图经纬度
const getClickLonLat = (lonlat) =>{
  clickLonLat.value = lonlat;
}
//显示查询面板
const showQueryDivBool = ref(true);
const showQueryDiv = (bool)=>{
  showQueryDivBool.value = bool;
}
const mapDrawType = ref("");//是否开启地图圈选查询类型（StopDraw关闭地图圈选 Circle圆形绘制 Polygon多边形绘制 Rectangle矩形绘制 Clear清空）
//地图圈选
function drawQueryGeomByType(type){
  mapDrawType.value = "Clear";
  setTimeout(function(){
    if(type=="圈选"){//绘制圆形区域
      mapDrawType.value = "Circle";
    }else if(type=="框选"){//绘制矩形区域
      mapDrawType.value = "Rectangle";
    }else if(type=="多边形"){//绘制多边形区域
      mapDrawType.value = "Polygon";
    }else if(type=="行政区划"){//地图点击位置获取省份名称
      mapDrawType.value = "Address";
    }
  },200);
}

//获取全部地图绘制结果
const getAllDrawGeom = (list) =>{
  mapDrawType.value = "StopDraw";
  let geom = "";
  if(list && list.length>0){
    geom = "MULTIPOLYGON(";
    for(let i=0;i<list.length;i++){
      if(i>0){
        geom += ",";
      }
      geom += list[i].split("POLYGON")[1];
    }
    geom += ")";
  }
  console.log("获取全部地图绘制结果");
  console.log(geom);
  if(geom=="MULTIPOLYGON()"){
    geom = "";
  }
  //全部地图绘制空间数据
  emits('getDrawGeom', geom);
}

//根据经纬度获取地址
function getLonLatAddress(addressComponent){
  //经纬度位置地址信息
  emits('getAddress', addressComponent);
}

/*地图传参end*/

//根据类型显示超图图层
function showLayerByDataType(type,sql){
  if(type){
    let sqlFilter = "";
    if(sql){
      sqlFilter = sql;
    }else{
      sqlFilter = "全部";
    }
    //移除图层数据
    removeLayerVersion(type);
    //设置图层数据版本
    // setLayerVersion(type,sqlFilter);
    setTimeout(function(){
      //设置图层数据版本
      setLayerVersion(type,sqlFilter);
    },200);
  }
}

//设置图层数据
function setLayerVersion(type,sqlFilter){
  let list = layerDataTypeList.value;
  for(let i=0;i<list.length;i++){
    if(list[i].level3DataType==type){
      list[i].versionCode = sqlFilter;
      list[i].show = true;
      break;
    }
  }
  console.log("设置图层数据");
  console.log(list);
  layerDataTypeList.value = list;
}

//移除图层数据
function removeLayerVersion(type){
  let list = layerDataTypeList.value;
  for(let i=0;i<list.length;i++){
    if(list[i].level3DataType==type){
      list[i].show = false;
      break;
    }
  }
  console.log(list);
  layerDataTypeList.value = list;
}

//按省市县进行查询定位
function searchAreas(province,city,county) {
  let key = "";
  let qcType = "";
  if(province) {
    if (city) {
      if (county) {
        key = county;
        qcType = "区县";
      }else{
        key = city;
        if(city==province){//直辖市：北京市、天津市、上海市、重庆市
          qcType = "省";
        }else{
          qcType = "市";
        }
      }
    }else{
      key = province;
      qcType = "省";
    }
  }else{
    key = "中国";
    qcType = "全国";
  }
  console.log("开始天地图搜索功能");
  //天地图搜索功能
  //let administrative1 = 'http://api.tianditu.gov.cn/administrative?postStr={"searchWord":"';
  //let administrative2 = '","searchType":"1","needSubInfo":"false","needAll":"false","needPolygon":"true","needPre":"true"}&tk=d21000f516e20e56b2a2b50596ecc1ee';
  let administrative1 = 'http://api.tianditu.gov.cn/v2/search?postStr={"keyWord":"';
  let administrative2 = '","queryType":12,"start":0,"count":10,"specify":"156110108"}&type=query&tk=0bfd57475542d76f12578a701d2a70ab';
  let url = administrative1 + key + administrative2;
  let httpRequest = new XMLHttpRequest();
  httpRequest.open('get', url, false); //第二步：打开连接
  httpRequest.send(null);
  if (httpRequest.status === 200) {
    let result = JSON.parse(httpRequest.responseText);
    //if (result.returncode == "100") {
    if (result.status.infocode == "1000"&&result.count>0) {
      let lonlat=result.area.lonlat;

      let value = lonlat.split(',');
      if (value.length === 2) {
        let lng = parseFloat(value[0]);
        if (isNaN(lng)) {
          return null;
        }
        let lat = parseFloat(value[1]);
        if (isNaN(lat)) {
          return null;
        }

        let LonLat = [lng, lat];
        //地图缩放级别
        let zoom = result.area.level;
        setMapCenterZoom(LonLat,zoom);
      }

      /*if (result.data && result.data.length > 0) {
        console.log("完成天地图搜索功能");
        console.log(result.data)
        if(result.data.length>1 && (qcType=='市' || qcType=='区县')){//有多个同名市、区县
          if(qcType=="市"){
            for(let i=0;i<result.data.length;i++){
              if(result.data[i].parents.province.name==province){
                let lng = result.data[i].lnt;
                let lat = result.data[i].lat;
                let zoom = result.data[i].level;
                let lonlat = [lng, lat];
                //设置地图定位显示
                setMapCenterZoom(lonlat,zoom);
                break;
              }
            }
          }else if(qcType=="区县"){
            for(let i=0;i<result.data.length;i++){
              if(result.data[i].parents.province.name==province && result.data[i].parents.city.name==city){
                let lng = result.data[i].lnt;
                let lat = result.data[i].lat;
                let zoom = result.data[i].level;
                let lonlat = [lng, lat];
                //设置地图定位显示
                setMapCenterZoom(lonlat,zoom);
                break;
              }
            }
          }
        }else{
          let lng = result.data[0].lnt;
          let lat = result.data[0].lat;
          let zoom = result.data[0].level;
          let lonlat = [lng, lat];
          //设置地图定位显示
          setMapCenterZoom(lonlat,zoom);
        }
      }*/
    }
  }
}

//设置地图定位显示
function setMapCenterZoom(lonlat,zoom){
  if(map.value!=null){
    map.value.getView().setCenter(lonlat);
    map.value.getView().setZoom(zoom);
  }
  loading.value = false;
  emits('returnQueryFlag',true);
}

//根据查询省市县设置地图定位显示
function setMapCenterZoomByQuery(value){
  loading.value = true;
  if(props.queryParams.province!="全国级"){
    let province = props.queryParams.province;
    let city = props.queryParams.city;
    let county = props.queryParams.county;
    //按省市县进行查询定位
    searchAreas(province,city,county);
  }else{
    //按省市县进行查询定位
    searchAreas(null,null,null);
  }
}

//获取查询条件
const getSqlFilter = watch(() => props.formSqlFilter, value => {// watch函数监听props.formSqlFilter
  console.log("获取查询参数");
  console.log(value);
  if(value){
    let dataType = props.dataType;
    //根据类型显示超图图层
    showLayerByDataType(dataType,value);
    //根据查询省市县设置地图定位显示
    setMapCenterZoomByQuery(value);
  }
},{immediate:true});

//获取地图圈选类型
const getDrawGeomType = watch(() => props.drawGeomType, value => {// watch函数监听props.drawGeomType
  if(value){
    drawQueryGeomByType(value);
  }
},{immediate:true});

onMounted(() => {
  completeRefreshData.value = true;
})
</script>

<style scoped lang="scss">
.mapDiv {
  width: 100%;
  /*height: 100%;*/
  position:absolute;
}

/*设置选择数据面板*/
.new-settingDiv {
  position:absolute;top:18px;left:110px;width:400px;padding:20px;padding-top: 10px;
  background:rgba(0,27,67,0.7);border-radius:4px;color:white;
}
.new-settingDiv-div1{
  padding-bottom: 10px;
  border-bottom: 1px dashed white;
}
.new-settingDiv .new-p{
  margin-bottom: 10px;
  font-size:14px;
}
.new-settingDiv-div3{
  text-align: center;
}
:deep(.new-settingDiv .el-radio){
  color:white;
}
:deep(.new-settingDiv .el-checkbox){
  color:white;
}
:deep(.new-settingDiv .new-p .el-button){
  position:absolute;right:20px;
}
:deep(.new-settingDiv .el-select){
  width:208px;
}
.new-settingDiv-span {
  float: right;
  line-height: 32px;
  cursor:pointer;
}
.new-settingDiv-span:hover {
  cursor:pointer;
}

/*带三角弹窗*/
.new-popover {
  position: absolute;
  top:0px;
  left:0px;
  padding:10px;
  background: rgba(0,27,67,0.8);
  color:white;
  z-index:100;
}
.new-triangle {
  position: absolute;
  top: 20px;
  left: -19px;
  overflow: hidden;
  width: 0;
  height: 0;
  border-width: 10px;
  border-style: dashed solid dashed dashed;
  border-color:transparent rgba(0,27,67,0.8) transparent transparent;
}

.new-pattenAnalysisDiv {
  position: absolute;top:246px;left:105px;font-size: 14px;
}

.new-pattenAnalysisDiv-button {
  float: left;
  width: 80px;
  text-align: center;
  padding: 5px;
  cursor:pointer;
}
/*规律分析按钮div*/
.showPattenAnalysisDiv{

}
.showPattenAnalysisDiv img {
  width:25px;
  border:1px dashed white;
}
.showPattenAnalysisDiv-div1 {
  display: inline-block;width:160px;border-bottom: 1px dashed white;padding-bottom: 10px;
}

.new-div-selected {
  background: rgba(16,124,229,0.5);
  border: 1px solid #707070;
}

.areaDialog {
  text-align: center;
  .close {
    text-align: right;
    .el-icon {
      color: #606266;
      padding: 20px 0;
      margin-right: 10px;
      right: 0px;
      font-size: 22px;
    }
  }
  width: 320px;
  position: absolute;
  top: 246px;
  left: 288px;
  background: rgba($color: #fff, $alpha: 0.9);
}

.resultShowButton {
  position:absolute;
  top:20px;
  right:20px;
  width:50px;
  height:50px;
}

</style>